package service

import (
	"context"
	"errors"
	"fmt"
	"lion-passport/internal/dao/model"
	"lion-passport/internal/dao/query"
	"lion-passport/internal/token"
	"lion-passport/internal/types"

	"gorm.io/gorm"
)

func VcodeLogin(req types.VcodeLoginRequest, ctx context.Context) (*types.LoginResponse, error) {

	if (req.Phone == "" || req.Code == "") {
		return nil, errors.New("missing phone number or code") // Phone login without phone number is not allowed
	}

	if (req.Code != "123456") {
		return nil, errors.New("验证码错误") // For simplicity, we assume the code is always "123456"
	}

	account, err := query.Account.Where(query.Account.Phone.Eq(req.Phone)).First()

	// account, err := accountDao.GetAccountByTypeAndOpenId(req.Type, req.OpenId)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// If account does not exist, create a new one
			account = &model.Account{
				Type:   "vcode",
				Phone: req.Phone,
				Status: 0,
			}

			if err := query.Account.Create(account); err != nil {
				return nil, fmt.Errorf("failed to create account: %w", err)
			}
		} else {
			return nil, fmt.Errorf("failed to query account: %w", err)
		}
	}

	accessToken, refreshToken, err := token.GenerateToken(*account)
	if err != nil {
		return nil, fmt.Errorf("failed to generate token: %w", err)
	}

	return &types.LoginResponse{
		AccessToken:  accessToken,
		RefreshToken: refreshToken,
	}, nil
}

func RefreshToken(refreshToken string, ctx context.Context) (*types.LoginResponse, error) {
	// Validate the refresh token
	if refreshToken == "" {
		return nil, errors.New("missing refresh token")
	}

	accessToken, refreshToken, err := token.ParseRefreshToken(refreshToken)

	if err != nil {
		return nil, errors.New(err.Error())
	}

	return &types.LoginResponse{
		AccessToken:  accessToken,
		RefreshToken: refreshToken,
	}, nil
}
